from flask import Flask, request, jsonify
from flask_cors import CORS
import os
from characters_data import characters
from openai_client import OpenAIClient, FreeAIClient, MockAIClient
from api_config_manager import APIConfigManager
from api_monitor import APIMonitor
from security import SecurityManager
from models import Character, ChatRequest, AIConfig
import time

app = Flask(__name__)
CORS(app)

# 初始化管理器
api_config_manager = APIConfigManager()
api_monitor = APIMonitor()
security_manager = SecurityManager()

# 初始化客户端
openai_client = OpenAIClient()
freeai_client = FreeAIClient()
mock_client = MockAIClient()

@app.route('/api/characters', methods=['GET'])
def get_characters():
    """获取角色列表"""
    search_query = request.args.get('search', '')
    
    if search_query:
        filtered_chars = [char for char in characters 
                         if search_query.lower() in char.name.lower() 
                         or search_query.lower() in char.description.lower()]
    else:
        filtered_chars = characters
    
    return jsonify([char.to_dict() for char in filtered_chars])

@app.route('/api/chat', methods=['POST'])
def chat():
    """处理聊天消息"""
    start_time = time.time()
    
    try:
        data = request.json
        chat_request = ChatRequest(**data)
        
        # 查找角色
        character = next((char for char in characters if char.id == chat_request.character_id), None)
        if not character:
            api_monitor.record_request('chat', False, time.time() - start_time)
            return jsonify({'success': False, 'error': '角色不存在'}), 404
        
        # 根据AI配置选择客户端
        ai_config = chat_request.ai_config or AIConfig()
        provider = ai_config.provider
        
        if provider == 'openai':
            # OpenAI
            api_key = ai_config.openai_api_key
            if not api_key:
                api_monitor.record_request('chat', False, time.time() - start_time)
                return jsonify({'success': False, 'error': '未提供OpenAI API密钥'})
            
            try:
                reply = openai_client.generate_response(
                    character=character,
                    message=chat_request.message,
                    skill=chat_request.skill,
                    history=chat_request.history,
                    api_key=api_key
                )
                api_monitor.record_request('chat', True, time.time() - start_time)
                return jsonify({'success': True, 'reply': reply})
                
            except Exception as e:
                # OpenAI调用失败，根据配置决定是否回退
                if ai_config.use_mock_fallback:
                    # 回退到模拟模式
                    reply = mock_client.generate_response(
                        character=character,
                        message=chat_request.message,
                        skill=chat_request.skill,
                        history=chat_request.history
                    )
                    api_monitor.record_request('chat', True, time.time() - start_time)
                    return jsonify({
                        'success': True, 
                        'reply': reply,
                        'fallback': True,
                        'original_error': str(e)
                    })
                else:
                    api_monitor.record_request('chat', False, time.time() - start_time)
                    return jsonify({'success': False, 'error': f'OpenAI API错误: {str(e)}'})
                    
        elif provider == 'free_ai':
            # Hugging Face（免费）
            try:
                reply = freeai_client.generate_response(
                    character=character,
                    message=chat_request.message,
                    skill=chat_request.skill,
                    history=chat_request.history
                )
                api_monitor.record_request('chat', True, time.time() - start_time)
                return jsonify({'success': True, 'reply': reply})
            except Exception as e:
                # 免费服务失败回退到模拟模式
                reply = mock_client.generate_response(
                    character=character,
                    message=chat_request.message,
                    skill=chat_request.skill,
                    history=chat_request.history
                )
                api_monitor.record_request('chat', True, time.time() - start_time)
                return jsonify({
                    'success': True, 
                    'reply': reply,
                    'fallback': True,
                    'original_error': str(e)
                })
                
        else:
            # 使用模拟模式
            reply = mock_client.generate_response(
                character=character,
                message=chat_request.message,
                skill=chat_request.skill,
                history=chat_request.history
            )
            api_monitor.record_request('chat', True, time.time() - start_time)
            return jsonify({'success': True, 'reply': reply})
        
    except Exception as e:
        api_monitor.record_request('chat', False, time.time() - start_time)
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/config', methods=['GET'])
def get_api_config():
    """获取API配置"""
    try:
        # 返回非敏感配置信息
        config = api_config_manager.config.copy()
        
        # 隐藏敏感信息
        if 'providers' in config:
            for provider in config['providers']:
                if 'api_key' in config['providers'][provider]:
                    del config['providers'][provider]['api_key']
        
        return jsonify({'success': True, 'config': config})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/config', methods=['POST'])
def update_api_config():
    """更新API配置"""
    try:
        data = request.json
        updates = data.get('updates', {})
        
        # 验证权限
        token = request.headers.get('Authorization', '').replace('Bearer ', '')
        if not security_manager.verify_api_token(token):
            return jsonify({'success': False, 'error': 'Unauthorized'}), 401
        
        # 应用更新
        for key, value in updates.items():
            if key in api_config_manager.config:
                api_config_manager.config[key] = value
        
        if api_config_manager.save_config():
            return jsonify({'success': True})
        else:
            return jsonify({'success': False, 'error': 'Failed to save config'})
            
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/test-connection', methods=['POST'])
def test_api_connection():
    """测试API连接"""
    try:
        data = request.json
        provider = data.get('provider')
        api_key = data.get('api_key')
        
        if not provider or not api_key:
            return jsonify({'success': False, 'error': 'Missing provider or API key'})
        
        if api_config_manager.validate_api_key(provider, api_key):
            return jsonify({'success': True})
        else:
            return jsonify({'success': False, 'error': 'Invalid API key or connection failed'})
            
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/usage-stats', methods=['GET'])
def get_usage_stats():
    """获取使用统计"""
    try:
        provider = request.args.get('provider', 'all')
        time_window = int(request.args.get('window', 3600))
        
        if provider == 'all':
            stats = {}
            for prov in api_config_manager.config['providers']:
                stats[prov] = api_monitor.get_usage_stats(prov, time_window)
        else:
            stats = api_monitor.get_usage_stats(provider, time_window)
        
        return jsonify({'success': True, 'stats': stats})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=8000)